/**
 * java多线程模式
 * @author andy.rong
 * Q 7-6
 */

package com.myjavalab.thread;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class ThreadPerMessagePatternMiniServer {
	public static void main(String[] args) {
        try {
            new MiniServer(8888).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
	}
}

class MiniServer {
	private final int portNumber;
	
	public MiniServer(int portNumber) {
		this.portNumber = portNumber;
	}
	
	public void execute() throws IOException {
		ServerSocket serverSocket = new ServerSocket(portNumber);
		System.out.println("Listening on " + portNumber);
		try {
			while(true) {
				System.out.println("Accepting...");
				Socket clientSocket = serverSocket.accept();
				System.out.println("Connected to " + clientSocket);
				try {
					Service2.service(clientSocket);
				}catch(IOException e) {
					e.printStackTrace();
				}
			}
		}catch (IOException e) {
			e.printStackTrace();
		}finally {
			serverSocket.close();
		}
	}
}

class Service2 {
	private Service2(){
		
	}
	public static void service(final Socket clientSocket) throws IOException {
		new Thread(){
			public void run() {
				try{
					doService(clientSocket);
				}catch (IOException e) {
					e.printStackTrace();
				}
			}
		}.start();
	}
	
	public static void doService(Socket clientSocket) throws IOException {
		System.out.println(Thread.currentThread().getName() + ":Service.service(" + clientSocket + ") Begin");
		try {
			DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
			out.writeBytes("HTTP/1.0 200 OK\r\n");
			out.writeBytes("Content-type: text/html\r\n");
			out.writeBytes("\r\n");
			out.writeBytes("<html><head><title>Countdown</title></head><body>\r\n");
			out.writeBytes("<h1>Countdown start!</h1>");
            for (int i = 10; i >= 0; i--) {
                System.out.println(Thread.currentThread().getName() + ": Countdown i = " + i);
                out.writeBytes("<h1>" + i + "</h1>");
                out.flush();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                }
            }
            out.writeBytes("</body></html>");
		}finally {
            clientSocket.close();
        }
        System.out.println(Thread.currentThread().getName() + ": Service.service(" + clientSocket + ") END");
	}
	
}
